﻿using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace CommLib.Mail
{
    public class Smtp
    {
        /// <summary>
        /// 发送smtp电子邮件
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="port">端口</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="domain">域名可为空</param>
        /// <param name="from">发送人</param>
        /// <param name="to">接收人</param>
        /// <param name="title">标题</param>
        /// <param name="body">正文</param>
        /// <param name="encoding">编码</param>
        /// <param name="isBodyHtml">是否为html格式</param>
        /// <param name="attachments">附件</param>
        /// <param name="sendMethod">发送电子邮件方式</param>
        /// <param name="enableSsl">是否使用ssl</param>
        /// <exception cref="System.ArgumentException"></exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        /// <exception cref="System.FormatException"></exception>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <returns></returns>

        public static async Task Send(string host, int port, string userName, string password, string domain,
            string from, string to, string title, string body, Encoding encoding, bool isBodyHtml=true,
            List<Attachment> attachments=null,
            SmtpDeliveryMethod sendMethod = SmtpDeliveryMethod.Network, bool enableSsl = false)
        {
            if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to))
                return;
            using (var smtp = new SmtpClient())
            {
                smtp.DeliveryMethod = sendMethod;
                smtp.EnableSsl = enableSsl;
                smtp.Host = host;
                smtp.Port = port;
                smtp.Credentials = string.IsNullOrEmpty(domain)
                    ? new NetworkCredential(userName, password)
                    : new NetworkCredential(userName, password, domain);
                using (var message = new MailMessage(from, to))
                {
                    message.Subject = title;
                    message.SubjectEncoding = encoding ?? Encoding.UTF8;
                    message.Body = body;
                    message.BodyEncoding = encoding ?? Encoding.UTF8;
                    message.IsBodyHtml = isBodyHtml;
                    message.Attachments.Clear();
                    attachments?.ForEach(x =>
                    {
                        message.Attachments.Add(x);
                    });
                    await smtp.SendMailAsync(message);
                }
            }
            await Task.FromResult(0);
        }
    }
}
